package com.hilinos.common.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ObjectUtils;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;

@Slf4j
public class IpUtils {

    private static final String IP_REGEX = "" + "^(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|[1-9])\\."
            + "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\." + "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\."
            + "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)$";

    public static boolean isIp(String ipStr) {
        return ipStr.matches(IP_REGEX);
    }

    /**
     * 获取当前主机的ip
     *
     * @return
     */
    public static String getLocalIp() {
        try {
            Enumeration<NetworkInterface> interfs = NetworkInterface.getNetworkInterfaces();
            while (interfs.hasMoreElements()) {
                NetworkInterface interf = interfs.nextElement();
                Enumeration<InetAddress> addres = interf.getInetAddresses();
                while (addres.hasMoreElements()) {
                    InetAddress in = addres.nextElement();
                    if (in instanceof Inet4Address) {
                        String host = in.getHostAddress();
                        if (!ObjectUtils.isEmpty(host) && host.matches(IP_REGEX) && !host.startsWith("127.0.0.")) {
                            return host;
                        }
                    }
                }
            }
        } catch (Exception e) {
            log.error("[IP]执行失败", e);
        }
        return null;
    }

    public static int[] getLocalIpArr() {
        String ip = getLocalIp();
        if (!ObjectUtils.isEmpty(ip)) {
            String[] iparr = ip.split("\\.");
            int[] iparrInt = new int[iparr.length];
            for (int i = 0; i < iparr.length; i++) {
                iparrInt[i] = Integer.parseInt(iparr[i]);
            }
            return iparrInt;
        }
        return null;
    }

}
